<template>
  <div>
    <el-upload
      v-model:file-list="fileList"
      class="avatar-uploader"
      :action="UPLOAD_URL"
      :limit="limit"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
    >
      <el-button type="primary">{{
        limit == 1 ? "单文件上传" : "多文件上传"
      }}</el-button>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { UPLOAD_URL } from "@/constants/BaseConstants";
import { ref, watch } from "vue";
import { ElMessage, UploadFile, UploadFiles } from "element-plus";

defineOptions({
  name: "文件上传"
});

const props = defineProps({
  value: {
    type: [Array, String]
  },
  limit: {
    type: Number,
    default: 1
  }
});

const fileList = ref<any[]>([]);
// 监听 props 的变化，更新本地副本
watch(
  () => props.value,
  newValue => {
    if (Array.isArray(newValue)) {
      fileList.value = newValue;
    } else {
      fileList.value = [
        {
          name: newValue,
          url: newValue
        }
      ];
    }
  }
);

function handleUploadSuccess(
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) {
  uploadFile.url = response.url;
  uploadFile.name = response.original_name;
  emits(
    "updateFileUrl-event",
    uploadFiles.map(item => {
      return {
        url: item.url,
        name: item.url
      };
    })
  );
}

function handleRemove(_: UploadFile, uploadFiles: UploadFiles) {
  emits(
    "updateFileUrl-event",
    uploadFiles.map(item => {
      return {
        url: item.url,
        name: item.name
      };
    })
  );
}

function handleExceed() {
  ElMessage.warning(`文件上传超过限制`);
}

const emits = defineEmits(["updateFileUrl-event"]);
</script>
